//	--------------------------------------------------------------------
//	Copyright(C) 2006,2007 Zhao Yukun. All rights reserved.
//	This file is a part of the Xeres system.
//	Xeres 2007
//	Contact : xeres.engine@gmail.com
//	$(reservedInfo)
//	$(reservedDeclaration)
//	--------------------------------------------------------------------
///	@file	<CRenderTargetSet10.cpp>
///	@path	~/src/graphics/dx10/
///	@date	2009/01/24
///	@desc	.

#include "config/config.h"

#include "graphics/RenderContext.h"
#include "graphics/dx10/CRenderTargetSet10.h"

namespace xeres {
	
	IMPL_IOBJECT_CLASS( CRenderTargetSet10 );

	// CRenderTargetSet10
	CRenderTargetSet10::CRenderTargetSet10( int width , int height , ID3D10DepthStencilView * pDSV )
		: m_width( width ) , m_height( height ) , m_pDSV( pDSV )
	{
	}
	// ~CRenderTargetSet10
	CRenderTargetSet10::~CRenderTargetSet10( void )
	{
		if( m_pDSV )
		{
			UINT rest = m_pDSV->Release();
			if( rest != 0 )
			{
				TRACE_ERROR( _S("CRenderTargetSet10::DTOR: Invalid ID3D10DepthStencilView reference count.") );
				FATAL_ABORT( _S("Invalid ID3D10DepthStencilView reference count.") );
			}
		}
	}
	// GetSize
	Pair<int> CRenderTargetSet10::GetSize( void )
	{
		return Pair<int>( m_width , m_height );
	}
	// GetCount
	uint CRenderTargetSet10::GetCount( void )
	{
		return D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT;
	}
	// BindTarget
	void CRenderTargetSet10::BindTarget( uint index , RefWeak<IRenderTarget> target )
	{
		XS_ASSERT( index < D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT );
		m_slots[index] = target;
	}
	// UnbindAll
	void CRenderTargetSet10::UnbindAll( void )
	{
		for( uint i = 0 ; i < D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT ; ++i )
			m_slots[i] = NULL;
	}
	// ApplyTarget
	void CRenderTargetSet10::ApplyTarget( RenderContext& rc )
	{
		ID3D10Device * dx = rc.GetDX10();

		ID3D10RenderTargetView * rts[D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT] = {0};
		uint binded = 0;

		for( uint i = 0 ; i < D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT ; ++i )
		{
			ID3D10RenderTargetView * rt = NULL;
			if( m_slots[i].IsValid() )
			{
				IUnknown * res = m_slots[i]->GetRenderTargetInterface();
				if( res )
				{
					res->QueryInterface( IID_ID3D10RenderTargetView , (void**)&rt );
				}
			}
			if( rt )
			{
				rts[binded] = rt;
				++binded;
			}
		}
		
		dx->OMSetRenderTargets( binded , rts , m_pDSV );

		for( uint i = 0 ; i < binded ; ++i )
			rts[i]->Release();
	}
	
} // namespace xeres
